<?php

namespace App\Console\Commands;

use App\Models\Circle;
use Illuminate\Console\Command;

class RecCircleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rec-circle';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info('-----------start-rec-circle-----------------------------');
        $two_day_ago = date("Y-m-d 00:00:01",strtotime("-2 day"));
        $yesterday = date("Y-m-d 23:59:59",strtotime("-1 day"));
        Circle::withCount(['article' => function($q) use($two_day_ago, $yesterday) {
            $q->where('articles.created_at', '>=', $two_day_ago)->where('articles.created_at', '<=', $yesterday);
        }])->chunk(20, function ($list) use($two_day_ago, $yesterday) {
            foreach ($list as $item) {
                $rec_weight = $item->join_count ? round($item->article_count / $item->join_count, 2) * 100 : 0 ;
                $item->rec_weight = $rec_weight;
                $item->save();
            }
        });
        \Log::info('-----------end-rec-circle-----------------------------');
    }
}
